package webdemo;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class PerformanceTest {
    /** Number of threads to be created */
    static final int THREADS = 10;
    /** Packets to be sent per thread */
    static final int PACKETS = 500;
    /** The interval of two packets been sent for each thread */
    private static final int INTERVAL = 80;
    private static final String DATA = "5a76d93cb435fc54eba0b97156fe38f432a4e1da3a87cce8a222644466ed1317";

    private class Sender implements Runnable {
        private InetAddress address = null;
        private DatagramSocket socket = null;
        private String msg = null;
        private String name = null;
        private int packet_sent = 0;

        public Sender(String addr, String msg, String name) throws SocketException,
                UnknownHostException {
            this.address = InetAddress.getByName(addr);
            this.socket = new DatagramSocket();
            this.msg = msg;
            this.name = name;
        }

        @Override
        public void run() {
            // send request
            byte[] buf = msg.getBytes();
            DatagramPacket packet = new DatagramPacket(buf, buf.length,
                    address, 60001);
            try {
                for (int i = 0; i < PerformanceTest.PACKETS; i++) {
                    socket.send(packet);
                    packet_sent++;
                    Thread.sleep(INTERVAL);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //System.out.println("Thread " + name + " sends " + packet_sent + " packets.");
            //System.out.println("Thread " + name + " end!");
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        args = new String[1];
        args[0] = "127.0.0.1";
        String msg; 
        for (int i = 0; i < THREADS; i++) {
            if(i % 2 == 0){
                msg = i + "_" + (i+1) + "\r\n" + (i+1) + "_" + i + "\r\n" + DATA;
            }else{
                msg = i + "_" + (i-1) + "\r\n" + (i-1) + "_" + i + "\r\n" + DATA;
                msg ="2cn_sz000826_1=1030391|10:58:18.770|28.780|399|11483.220|1521227|1527482|0|9,1030392|10:58:18.770|28.780|601|17296.780|1526960|1527482|0|9";
            }
            try {
                new Thread(new PerformanceTest().new Sender(args[0], msg, "" + i)).start();
            } catch (SocketException e) { 
                e.printStackTrace();
            } catch (UnknownHostException e) { 
                e.printStackTrace();
            }
        } 
    }
}
